﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;


/// <summary>
/// 对象池基类
/// TODO:将列表改成数组
/// </summary>
public class ObjPool<T> where T : class, IPoolItem, new()
{
    public List<T> SpareObjs { get; private set; }

    public List<T> WorkingObjs { get; private set; }

    public int NormalSize;

    public bool IsAutoReduce = true;

    protected int autoExtendSize = 10;

    protected bool isInit;

    /// <summary>生成的池中物品的ID</summary>
    protected int IdIndex;

    public ObjPool(int capacity)
    {
        NormalSize = capacity;
    }

    protected virtual void Init(int capacity)
    {
        SpareObjs = new List<T>(capacity);
        WorkingObjs = new List<T>();
        NormalSize = capacity;
        for (int i = 0; i < capacity; i++)
        {
            T obj = CreateTargetObj();
            obj.IsActive=false;
            SpareObjs.Add(obj);
        }
    }

    public void AutoReduceCount()
    {
        if (IsAutoReduce)
        {
            if (SpareObjs != null && SpareObjs.Count > NormalSize)
            {
                SpareObjs[0].Dispose();
                SpareObjs.RemoveAt(0);
            }
        }
    }

    public virtual T GetObjFromPool()
    {
        if (!isInit)
        {
            Init(NormalSize);
        }
        if (SpareObjs != null)
        {
            T returnObj;
            if (SpareObjs.Count > 0)
            {
                returnObj = SpareObjs[0];
                returnObj.IsActive=true;
                returnObj.OnEnable();
            }
            else
            {
                DebugUtils.LogRedInfo("当前池中无东西");
                returnObj = CreateTargetObj();
            }
            WorkingObjs.Add(returnObj);
            return returnObj;
        }
        else
        {
            return null;
        }
    }

    protected virtual T CreateTargetObj()
    {
        return new T();
    }

    public void RemoveObjToPool(T obj)
    {
        if (SpareObjs != null)
        {
            obj.IsActive=false;
            obj.OnDisable();
            SpareObjs.Add(obj);
            WorkingObjs.Remove(obj);
            AutoReduceCount();
        }
    }
}

